package com.dymedia.aibo.mvp.ui.widget;

import android.content.Context;
import android.os.Handler;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.dymedia.aibo.R;
import com.dymedia.aibo.app.MainApp;
import com.dymedia.aibo.mvp.model.Entity.Group;
import com.dymedia.aibo.mvp.model.Entity.Video;
import com.dymedia.aibo.mvp.ui.adapter.GroupAdapter;
import com.dymedia.aibo.mvp.ui.adapter.VideoAdapter;

import java.util.ArrayList;
import java.util.List;

import me.jessyan.art.mvp.Message;
import me.jessyan.art.utils.ArtUtils;
import timber.log.Timber;

import static com.dymedia.aibo.mvp.presenter.ChannelPresenter.MSG_ACTION_VIDEO_PLAY;

public class VideoMenuView extends LinearLayout {
    GridLayoutManager mLayoutManager;
    LinearLayoutManager mLayoutManagerGroup;

    RecyclerView recyclerViewVideo;
    RecyclerView recyclerViewGroup;
    VideoAdapter mAdapter;
    GroupAdapter mAdapterGroup;

    Handler mVisHandler = new Handler();
    Handler mHandler = new Handler();

    List<Group> mDatas;
    Message mCallbackMessage = null;

    public static int columnNum = 4;
    public void setCallback(Message callbackMessage) {
        mCallbackMessage = callbackMessage;
    }

    public VideoMenuView(Context context) {
        super(context);
        init();
    }

    public VideoMenuView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public void setDatas(List<Group> groups) {
        mAdapterGroup.getInfos().clear();
        mAdapterGroup.getInfos().addAll(groups);
        mDatas = groups;
    }

    public void notifyDataSetChanged() {
        Timber.d("notifyDataSetChanged");
        mAdapterGroup.notifyDataSetChanged();
        recyclerViewGroup.requestFocus();
        View v2 = (View)recyclerViewGroup.getTag();
        if (v2 != null)
            v2.requestFocus();
    }

    public boolean isShow() {
        return getVisibility() == View.VISIBLE;
    }

    public void show() {
        ((View)getParent()).setVisibility(View.VISIBLE);
        setVisibility(View.VISIBLE);
    }

    //焦点处理注意：
    // 父窗口android:focusable="true"，此时recycleView不会自动获取
    // 父窗口从隐藏到显示，recycleView会自动获取一次焦点
    public void hide() {
        isChannelFocus = false;
        setVisibility(View.GONE);
//        recyclerViewVideo.setTag(null);
//        recyclerViewGroup.setTag(null);
    }

    boolean isChannelFocus = false;

    private void init() {
        View rootView = LayoutInflater.from(getContext()).inflate(R.layout.widget_videomenu, this);
        recyclerViewVideo = rootView.findViewById(R.id.recyclerViewVideo);
        recyclerViewGroup = rootView.findViewById(R.id.recyclerViewGroup);

        this.mAdapter = new VideoAdapter(new ArrayList<>());
        this.mAdapterGroup = new GroupAdapter(new ArrayList<>());

        mLayoutManager = new FocusGridLayoutManager(getContext(), columnNum);
        ArtUtils.configRecyclerView(recyclerViewVideo, mLayoutManager);
        recyclerViewVideo.setAdapter(mAdapter);
        mAdapter.setFocusChangeListener((position, hasFocus) -> {
            Timber.d("mAdapter, onFocusChange, currentPosition: " + position + ", hasFocus: " + hasFocus);
            View v = mLayoutManager.findViewByPosition(position);
            if (hasFocus) {
                recyclerViewVideo.setTag(v);
//                View groupView = (View) recyclerViewGroup.getTag();
//                if (groupView != null) {
//                    groupView.setBackgroundColor(Color.RED);
//                }
            }
        });
        mAdapter.setKeyChangeListener((v, keyCode, event) -> {
            if (event.getAction() == KeyEvent.ACTION_DOWN) {
                switch (keyCode) {
                    case KeyEvent.KEYCODE_DPAD_DOWN:
                    case KeyEvent.KEYCODE_DPAD_UP:
                        mVisHandler.removeCallbacksAndMessages(null);
                        isChannelFocus = true;
                        break;
                    case KeyEvent.KEYCODE_DPAD_LEFT:
                        mVisHandler.removeCallbacksAndMessages(null);
                        View v5 = (View) recyclerViewVideo.getTag();
                        if (v5 != null && ((Integer) v5.getTag()) % columnNum == 0) {
                            isChannelFocus = false;
                            View v2 = (View) recyclerViewGroup.getTag();//分组焦点
                            if (v2 != null)
                                v2.requestFocus();
                        }
                        break;
                    case KeyEvent.KEYCODE_DPAD_RIGHT:
                        break;
                    case KeyEvent.KEYCODE_DPAD_CENTER:
                    case KeyEvent.KEYCODE_ENTER:
                        View v3 = (View) recyclerViewGroup.getTag();
                        View v4 = (View) recyclerViewVideo.getTag();
                        if (v3 != null && v4 != null) {
                            playAction((int) v3.getTag(), (int) v4.getTag());
                        }
                        break;
                    default:
                        mVisHandler.removeCallbacksAndMessages(null);
                        break;
                }
            }
            return false;
        });
        mAdapter.setClickedListener(v -> {
            View v3 = (View) recyclerViewGroup.getTag();
            View v4 =  v;
            if (v3 != null && v4 != null)
                playAction((int) v3.getTag(), (int)v4.getTag());
        });

        recyclerViewVideo.getViewTreeObserver().addOnPreDrawListener(() -> {
//            if (recyclerViewVideo.getHeight() > MainApp.padding)
//                MainApp.recycleViewHeight = recyclerViewVideo.getHeight() - MainApp.padding;
            return true;
        });

        mLayoutManagerGroup = new LinearLayoutManager(getContext());
        ArtUtils.configRecyclerView(recyclerViewGroup, mLayoutManagerGroup);
        recyclerViewGroup.setAdapter(mAdapterGroup);
        mAdapterGroup.setFocusChangeListener((position, hasFocus) -> {
            Timber.d("mAdapterGroup, onFocusChange, currentPosition: " + position + ", hasFocus: " + hasFocus);
            View v = mLayoutManagerGroup.findViewByPosition(position);
            View v2 = (View)recyclerViewGroup.getTag();
            if (hasFocus){
                if (v2 != null){ // 颜色
                    ((TextView)v2.findViewById(R.id.tv_name)).setTextColor(getResources().getColor(R.color.listItemTextColor));
                }
                if (v != null)
                    ((TextView)v.findViewById(R.id.tv_name)).setTextColor(getResources().getColor(R.color.listItemTextFocusColor));

                mHandler.post(() -> {
                    if (position >= 0 && position < mDatas.size()) {
                        recyclerViewGroup.setTag(v);
                        mAdapter.getInfos().clear();
                        mAdapter.getInfos().addAll(mDatas.get(position).videos);
                        mAdapter.notifyDataSetChanged();
                    }
                });
            }
        });
        mAdapterGroup.setKeyChangeListener((v, keyCode, event) -> {
            if (event.getAction() == KeyEvent.ACTION_DOWN) {
                switch (keyCode) {
                    case KeyEvent.KEYCODE_DPAD_DOWN:
                        View focusItem = (View) recyclerViewGroup.getTag();
                        if (focusItem != null) {//禁止下键跳转到频道列表
                            Integer position = (Integer) focusItem.getTag();
                            if (position >= mAdapterGroup.getInfos().size() - 1) {
                                return true;
                            }
                        }
                        //View v = FocusFinder.getInstance().findNextFocus(TvMenuView.this, (View)recyclerViewGroup.getTag(), FOCUS_RIGHT);
                        break;
                }
            }
            return false;
        });
    }

    private void playAction(int groupIndex, int itemIndex) {
        if (groupIndex >= 0 && groupIndex < mDatas.size() && itemIndex >= 0 && itemIndex < mDatas.get(groupIndex).videos.size()) {
            Video c = mDatas.get(groupIndex).videos.get(itemIndex);
            if (c != null && mCallbackMessage != null) {
                mCallbackMessage.obj = c;
                mCallbackMessage.what = MSG_ACTION_VIDEO_PLAY;
                mCallbackMessage.handleMessageToTargetUnrecycle();
            }
        }
    }
}
